package com.sumainfor.zuul.conf;

import com.baomidou.mybatisplus.spring.MybatisMapperRefresh;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileUrlResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;

/**
 * @Author PuaChen
 * @Create 2018-12-20 15:38
 */

@SpringBootConfiguration
@ConditionalOnProperty(name = "mybatis-plus.global-config.refresh-mapper",havingValue = "true")
public class DevFlushMyBatisXmlZuul {
    /**
     * 热部署
     *
     * @param factory
     * @return
     */
    @Bean
    public MybatisMapperRefresh mapperRefresh(@Autowired SqlSessionFactory factory) throws IOException {
        System.out.println("\n" +
                "   _____ _             _     __  __       _           _   _      __   __          _ \n" +
                "  / ____| |           | |   |  \\/  |     | |         | | (_)     \\ \\ / /         | |\n" +
                " | (___ | |_ __ _ _ __| |_  | \\  / |_   _| |__   __ _| |_ _ ___   \\ V / _ __ ___ | |\n" +
                "  \\___ \\| __/ _` | '__| __| | |\\/| | | | | '_ \\ / _` | __| / __|   > < | '_ ` _ \\| |\n" +
                "  ____) | || (_| | |  | |_  | |  | | |_| | |_) | (_| | |_| \\__ \\  / . \\| | | | | | |\n" +
                " |_____/ \\__\\__,_|_|   \\__| |_|  |_|\\__, |_.__/ \\__,_|\\__|_|___/ /_/ \\_\\_| |_| |_|_|\n" +
                "                                     __/ |                                          \n" +
                "                                    |___/                                           \n");
        System.err.println("已开启MyBatis XML 热加载 \n\n\n\n");
        ClassPathResource resource = new ClassPathResource("mapper");
        File[] files = resource.getFile().listFiles(pathname -> pathname.getName().endsWith(".xml"));
        Resource[] res = new Resource[files.length];
        for (int i = 0; i < files.length; i++) {
            res[i] = new FileUrlResource(files[i].getAbsolutePath());
        }
        MybatisMapperRefresh refresh = new MybatisMapperRefresh(res, factory, 5, 2, true);
        return refresh;
    }
}
